package com.olympus.hermes.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author Mickey
 * @since 2021/1/21
 */
@Configuration
public class ObjectMapperConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return new Jackson2ObjectMapperBuilder()
                //字段单词下划线隔开
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                //Long类型 转换String
                .serializerByType(Long.class, ToStringSerializer.instance)
                //Instant类型 转换成字符串时间
                .serializerByType(Instant.class, new InstantCustomSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                //过滤null的字段
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .build();
    }

    public static class InstantCustomSerializer extends JsonSerializer<Instant> {

        private final DateTimeFormatter format;

        private InstantCustomSerializer(DateTimeFormatter formatter) {
            this.format = formatter;
        }

        @Override
        public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (instant == null) {
                return;
            }
            String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
            jsonGenerator.writeString(jsonValue);
        }
    }
}
